package com.min.oss.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.log.Log;
import com.min.oss.config.OssProperties;
import io.minio.*;
import javafx.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;

/**
 * MinIO对象存储
 * @author: fengt
 * @date: 2021/4/23 18:21
 **/
public class MinioService implements StorageService {

    private MinioClient instance;

    private static final String Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":" +
            "{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"," +
            "\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::%s\"]}," +
            "{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\"," +
            "\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::%s/*\"]}]}\n";

    Log log = Log.get();

    @Autowired
    OssProperties p;

    public MinioService() {
        instance = MinioClient.builder()
                .endpoint(p.getEndpoint())
                .credentials(p.getAccesskey(), p.getSecretKey())
                .build();
    }

    @Override
    public String save(InputStream is, String filename) {
        try {
            boolean isExist = instance.bucketExists(BucketExistsArgs.builder().bucket(p.getBucket()).build());
            if (!isExist) {
                instance.makeBucket(MakeBucketArgs.builder().bucket(p.getBucket()).build());
            }

            instance.putObject(PutObjectArgs.builder().bucket(p.getBucket()).object(filename).stream(is, is.available(), -1).build());
            return instance.getObjectUrl(p.getBucket(), filename);

        } catch (Exception ee) {
            log.error("存储文件流失败,文件：" + filename, ee);
        }

        return null;
    }

    @Override
    public boolean delete(String fileUrl) {
        Pair<String, String> pair = parseUrl(fileUrl);
        if (pair != null) {
            try {
                instance.removeObject(RemoveObjectArgs.builder().bucket(pair.getKey()).object(pair.getValue()).build());
                return true;
            } catch (Exception e) {
                log.error("删除文件失败："+ fileUrl, e);
            }
        }

        return false;
    }

    public static Pair<String, String> parseUrl(String url) {
        if (StrUtil.isNotBlank(url)) {
            String string = URLUtil.getDecodedPath(URLUtil.url(url));
            String[] strings = string.split("/", 3);
            if (strings.length == 3) {
                return new Pair(strings[1],strings[2]);
            }
        }
        return null;
    }
}
